﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace CMS6Tools.Common.Email
{ 
    public class XsltEmailTemplate : EmailTemplate
    {
        public string TemplateFilePathName
        {
            get;
            set;
        }

        protected XsltEmailTemplate()
        {
        }

        public XsltEmailTemplate(string templateFilePathName)
        {
            TemplateFilePathName = templateFilePathName;
        }

        public override string Transform(ITextTemplateExtraData extraData)
        {
            return TransformTemplateFromFile(extraData);
        }

        #region GetXslCompiledTransform
        protected virtual XslCompiledTransform GetXslCompiledTransform(string templateFilePath)
        {
            var result = new XslCompiledTransform();
            result.Load(templateFilePath);
            return result;
        }
        #endregion

        protected virtual string TransformTemplateFromFile(ITextTemplateExtraData extraData)
        {
            XslCompiledTransform objxslt = GetXslCompiledTransform(TemplateFilePathName);
            if (objxslt == null)
                return string.Empty;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.AppendChild(xmlDoc.CreateElement("DocumentRoot"));
            XPathNavigator xPathNav = xmlDoc.CreateNavigator();

            Hashtable table = new Hashtable();
            table["ext:Data"] = extraData ?? EmptyTextTemplateExtraData.Default;

            XsltArgumentList xslArg = new XsltArgumentList();
            if (table != null)
                foreach (DictionaryEntry entry in table)
                {
                    xslArg.AddExtensionObject(entry.Key.ToString(), entry.Value);
                }

            StringBuilder emailBuilder = new StringBuilder();

            try
            {
                using (XmlTextWriter xmlWriter = new XmlTextWriter(new System.IO.StringWriter(emailBuilder)))
                {
                    objxslt.Transform(xPathNav, xslArg, xmlWriter, null);
                    xmlWriter.Close();
                }
            }
            catch (XsltException ex)
            {
                return string.Empty;
            }

            return emailBuilder.ToString();
        }
    }
}
